package cn.view;

import cn.comon.CSVUtil;
import cn.comon.VerticalTextCellRenderer;
import cn.dao.PayDetailDao;
import cn.entity.PayDetail;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class PayDetailManageView extends JInternalFrame{
    JTable detail;
    DefaultTableModel model;
    JPanel Jbutton;
    public PayDetailManageView() {
        super("采购明细管理页面", false, true, false, true);
        initializeComponents();
        this.setSize(650, 500);
        this.setVisible(true);
    }

    private void initializeComponents() {
        // 设置布局管理器
        getContentPane().setLayout(new BorderLayout());
        // 初始化数据和按钮
        getDetailData();
        setButton();
    }

    private void getDetailData() {
        PayDetailDao dao = new PayDetailDao(); // 假设这是一个访问PayDetail表的DAO类
        List<Object[]> ls = dao.selectAll(); // 调整方法以从数据库获取所有采购明细记录
        String[] title = { "采购明细号", "采购清单号", "商品编号", "采购数量", "商品单价", "商品总价", "备注" }; // 根据PayDetail表结构调整列标题
        model = new DefaultTableModel(ls.toArray(new Object[][]{}), title);
        detail = new JTable(model);
        detail.setDefaultEditor(Object.class, null);
        detail.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        // 设置表格列宽
        setColumnWidths(detail, new int[]{100, 100,80, 70, 60, 60, 120});
        // 设置表格行高
        detail.setRowHeight(15);
        // 设置自定义渲染器
        for (int i = 0; i < detail.getColumnCount(); i++) {
            detail.getColumnModel().getColumn(i).setCellRenderer(new VerticalTextCellRenderer());
        }

        JScrollPane scrollPane = new JScrollPane(detail, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        getContentPane().add(scrollPane, BorderLayout.CENTER);
    }

    private void setColumnWidths(JTable table, int[] widths) {
        for (int i = 0; i < widths.length; i++) {
            table.getColumnModel().getColumn(i).setPreferredWidth(widths[i]);
        }
    }

    public void refreshPayDetailData(){
        PayDetailDao dao = new PayDetailDao();
        List<Object[]> ls = dao.selectAll();
        model.setRowCount(0);
        for (Object[] row : ls) {
            model.addRow(row);
        }
    }

    private PayDetail getPayDetailFromFields(JTextField[] fields) {
        PayDetail payDetail = new PayDetail();

        String didText = fields[0].getText().trim();
        if (!didText.isEmpty()) {
            payDetail.setDid(Integer.parseInt(didText));
        }

        String midText = fields[1].getText().trim();
        if (!midText.isEmpty()) {
            payDetail.setMid(Integer.parseInt(midText));
        }

        payDetail.setGid(fields[2].getText().trim()); // gid

        String dcountText = fields[3].getText().trim();
        if (!dcountText.isEmpty()) {
            payDetail.setDcount(Integer.parseInt(dcountText));
        }

        String priceText = fields[4].getText().trim();
        if (!priceText.isEmpty()) {
            payDetail.setPrice(Float.parseFloat(priceText));
        }

        payDetail.setNotes(fields[5].getText().trim()); // notes

        return payDetail;
    }



    private List<PayDetail> convertToPayDetailList(List<Object[]> data) {
        List<PayDetail> payDetails = new ArrayList<>();
        for (Object[] row : data) {
            PayDetail payDetail = new PayDetail();
            payDetail.setDid((int) row[0]); // 假设payId是int类型
            payDetail.setMid((int) row[1]);
            payDetail.setGid((String) row[2]);
            payDetail.setDcount(((int)row[3])); // 确保转型兼容不同数值类型
            payDetail.setPrice(((Number) row[4]).floatValue());
            payDetail.setGoodsTotal(((Number) row[5]).floatValue()); // 需要实现convertToDate方法来处理日期转换
            payDetail.setNotes((String) row[6]);
            payDetails.add(payDetail);
        }
        return payDetails;
    }

    private void showAddPayDetailDialog() {
        JTextField[] fields = new JTextField[5]; // 支付明细现在有5个字段（假设notes仍保留，但可能根据实际需要也可能移除）
        fields[0] = new JTextField(10);
        fields[1] = new JTextField(10);
        fields[2] = new JTextField(10);
        fields[3] = new JTextField(10);
        fields[4] = new JTextField(10);

        JPanel panel = new JPanel(new GridLayout(5, 2));
        panel.add(new JLabel("采购明细号:"));
        panel.add(fields[0]);
        panel.add(new JLabel("采购清单号:"));
        panel.add(fields[1]);
        panel.add(new JLabel("商品编号:"));
        panel.add(fields[2]);
        panel.add(new JLabel("采购数量:"));
        panel.add(fields[3]);
        panel.add(new JLabel("备注:"));
        panel.add(fields[4]);

        int result = JOptionPane.showConfirmDialog(null, panel, "添加支付明细", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            //PayDetail payDetail = getPayDetailFromFields(fields); // 假设这个方法已调整，不再包含商品单价和商品总价的获取
            PayDetail payDetail = new PayDetail();

            String didText = fields[0].getText().trim();
            if (!didText.isEmpty()) {
                payDetail.setDid(Integer.parseInt(didText));
            }

            String midText = fields[1].getText().trim();
            if (!midText.isEmpty()) {
                payDetail.setMid(Integer.parseInt(midText));
            }

            payDetail.setGid(fields[2].getText().trim()); // gid

            String dcountText = fields[3].getText().trim();
            if (!dcountText.isEmpty()) {
                payDetail.setDcount(Integer.parseInt(dcountText));
            }

            payDetail.setNotes(fields[4].getText().trim()); // notes

            PayDetailDao dao = new PayDetailDao(); // 支付明细数据库操作类
            List<PayDetail> payDetailsList = new ArrayList<>();
            payDetailsList.add(payDetail);
            dao.addPayDetail(payDetailsList); // 假设此方法用于添加支付明细到数据库，商品单价和总价由数据库计算

            // 更新表格视图，注意移除了商品单价和商品总价列
            model.addRow(new Object[]{
                    payDetail.getDid(),
                    payDetail.getMid(),
                    payDetail.getGid(),
                    payDetail.getDcount(),
                    // 下面两行被移除，因为商品单价和商品总价由数据库自动生成
                    // payDetail.getPrice(),
                    // payDetail.getGoodsTotal(),
                    payDetail.getNotes() // 假设notes仍需要显示，根据实际需求可调整
            });
            refreshPayDetailData();
        }
    }

    private void showEditPayDetailDialog(int selectedRow) throws SQLException {
        JTextField[] fields = new JTextField[6]; // Exclude GoodsTotal field
        fields[0] = new JTextField(10); // Did
        fields[1] = new JTextField(10); // Mid
        fields[2] = new JTextField(10); // Gid
        fields[3] = new JTextField(10); // Dcount
        fields[4] = new JTextField(10); // Price
        fields[5] = new JTextField(10); // Notes

        JPanel panel = new JPanel(new GridLayout(6, 2));
        panel.add(new JLabel("采购明细号:"));
        panel.add(fields[0]);
        panel.add(new JLabel("采购清单号:"));
        panel.add(fields[1]);
        panel.add(new JLabel("商品编号:"));
        panel.add(fields[2]);
        panel.add(new JLabel("采购数量:"));
        panel.add(fields[3]);
        panel.add(new JLabel("商品单价:"));
        panel.add(fields[4]);
        panel.add(new JLabel("备注:"));
        panel.add(fields[5]);

        // 填充现有支付明细数据至表单字段
        fields[0].setText(model.getValueAt(selectedRow, 0).toString()); // Did
        fields[1].setText(model.getValueAt(selectedRow, 1).toString()); // Mid
        fields[2].setText((String) model.getValueAt(selectedRow, 2)); // Gid
        fields[3].setText(model.getValueAt(selectedRow, 3).toString()); // Dcount
        fields[4].setText(model.getValueAt(selectedRow, 4).toString()); // Price
        fields[5].setText((String) model.getValueAt(selectedRow, 6)); // Notes

        // 显示修改确认对话框
        int result = JOptionPane.showConfirmDialog(null, panel, "修改支付明细", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            // 获取原始Did作为更新依据
            String originalDid = model.getValueAt(selectedRow, 0).toString();
            // 从表单字段中获取并创建PayDetail对象
            PayDetail payDetail = getPayDetailFromFields(fields);
            // 实例化PayDetailDao并调用更新方法
            PayDetailDao dao = new PayDetailDao();
            dao.updatePayDetail(payDetail, originalDid); // 执行更新操作，确保updatePayDetail方法签名与传参匹配
            // 成功更新后，刷新表格视图以反映最新数据
            model.setValueAt(payDetail.getDid(), selectedRow, 0);
            model.setValueAt(payDetail.getMid(), selectedRow, 1);
            model.setValueAt(payDetail.getGid(), selectedRow, 2);
            model.setValueAt(payDetail.getDcount(), selectedRow, 3);
            model.setValueAt(payDetail.getPrice(), selectedRow, 4);
            model.setValueAt(payDetail.getNotes(), selectedRow, 6);
        }
    }


    private void showQueryPayDetailDialog() {
        JTextField[] fields = new JTextField[7]; // 假设支付明细有7个字段，包括notes
        for (int i = 0; i < fields.length; i++) {
            fields[i] = new JTextField(10);
        }

        JPanel panel = new JPanel(new GridLayout(7, 2));
        panel.add(new JLabel("采购明细号:"));
        panel.add(fields[0]);
        panel.add(new JLabel("采购清单号:"));
        panel.add(fields[1]);
        panel.add(new JLabel("商品编号:"));
        panel.add(fields[2]);
        panel.add(new JLabel("采购数量:"));
        panel.add(fields[3]);
        panel.add(new JLabel("商品单价:"));
        panel.add(fields[4]);
        panel.add(new JLabel("商品总价:"));
        panel.add(fields[5]);
        panel.add(new JLabel("备注:"));
        panel.add(fields[6]);

        int result = JOptionPane.showConfirmDialog(null, panel, "查询支付明细", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            PayDetail criteria = getPayDetailFromFields(fields); // 修改为从字段获取查询条件的方法

            PayDetailDao dao = new PayDetailDao(); // 支付明细数据库操作类
            List<PayDetail> payDetailList = dao.queryPayDetails(criteria); // 查询支付明细信息

            if (payDetailList.isEmpty()) {
                JOptionPane.showMessageDialog(null, "没有符合的支付明细信息");
            } else {
                // 清空现有表格数据
                model.setRowCount(0);
                // 添加查询结果到表格
                for (PayDetail payDetail : payDetailList) {
                    model.addRow(new Object[]{
                            payDetail.getDid(), // 支付明细编号
                            payDetail.getMid(), // 采购清单编号
                            payDetail.getGid(), // 商品编号
                            payDetail.getDcount(), // 采购数量
                            payDetail.getPrice(), // 商品单价
                            payDetail.getGoodsTotal(), // 商品总价
                            payDetail.getNotes() // 备注
                    });
                }
            }
        }
    }

    private void showExportPayDetailDialog() {
        String[] options = {"导出所有支付明细数据", "导出筛选后的支付明细数据", "导出除筛选外的支付明细数据"};
        int choice = JOptionPane.showOptionDialog(
                null,
                "请选择导出选项",
                "导出支付明细数据",
                JOptionPane.DEFAULT_OPTION,
                JOptionPane.INFORMATION_MESSAGE,
                null,
                options,
                options[0]
        );

        if (choice == JOptionPane.CLOSED_OPTION) {
            return;
        }

        List<PayDetail> payDetailsToExport = new ArrayList<>();

        if (choice == 0) { // 导出所有支付明细数据
            PayDetailDao dao = new PayDetailDao();
            List<Object[]> allPayDetailData = dao.selectAll();
            payDetailsToExport = convertToPayDetailList(allPayDetailData);
        } else {
            JTextField[] fields = new JTextField[7];
            for (int i = 0; i < fields.length; i++) {
                fields[i] = new JTextField(10);
            }

            JPanel panel = new JPanel(new GridLayout(7, 2));
            panel.add(new JLabel("采购明细号:"));
            panel.add(fields[0]);
            panel.add(new JLabel("采购清单号:"));
            panel.add(fields[1]);
            panel.add(new JLabel("商品编号:"));
            panel.add(fields[2]);
            panel.add(new JLabel("采购数量:"));
            panel.add(fields[3]);
            panel.add(new JLabel("商品单价:"));
            panel.add(fields[4]);
            panel.add(new JLabel("商品总价:"));
            panel.add(fields[5]);
            panel.add(new JLabel("备注:"));
            panel.add(fields[6]);

            int result = JOptionPane.showConfirmDialog(null, panel, "筛选支付明细", JOptionPane.OK_CANCEL_OPTION);
            if (result == JOptionPane.CLOSED_OPTION || result == JOptionPane.CANCEL_OPTION) {
                return;
            }

            PayDetail criteria = getPayDetailFromFields(fields);
            PayDetailDao dao = new PayDetailDao();
            List<PayDetail> filteredPayDetails = dao.queryPayDetails(criteria);

            if (choice == 1) { // 导出筛选后的支付明细数据
                payDetailsToExport = filteredPayDetails;
            } else if (choice == 2) { // 导出除筛选外的支付明细数据
                List<Object[]> allPayDetailData = dao.selectAll();
                List<PayDetail> allPayDetails = convertToPayDetailList(allPayDetailData);
                allPayDetails.removeAll(filteredPayDetails);
                payDetailsToExport = allPayDetails;
            }
        }

        if (!payDetailsToExport.isEmpty()) {
            exportPayDetailsToCSV(payDetailsToExport); // 假设此方法用于导出支付明细数据到CSV
        } else {
            JOptionPane.showMessageDialog(null, "没有符合条件的支付明细数据可导出");
        }
    }

    private void exportPayDetailsToCSV(List<PayDetail> payDetails) {
        String[] headers = {"支付明细编号", "采购清单编号", "商品编号", "采购数量", "商品单价", "商品总价", "备注"};
        List<Object[]> data = new ArrayList<>();
        for (PayDetail payDetail : payDetails) {
            data.add(new Object[]{
                    payDetail.getDid(),
                    payDetail.getMid(),
                    payDetail.getGid(),
                    payDetail.getDcount(),
                    payDetail.getPrice(),
                    payDetail.getGoodsTotal(),
                    payDetail.getNotes()
            });
        }

        File csvFile = CSVUtil.createCSVFile(headers, data, "output/path", "支付明细数据");
        if (csvFile != null) {
            JOptionPane.showMessageDialog(null, "支付明细数据已成功导出到: " + csvFile.getAbsolutePath());
        } else {
            JOptionPane.showMessageDialog(null, "导出支付明细数据失败");
        }
    }

    private void setButton() {
        Jbutton = new JPanel();
        Jbutton.setLayout(new FlowLayout());

        JButton addPayDetailButton = new JButton("添加支付明细");
        addPayDetailButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                showAddPayDetailDialog();
            }
        });

        JButton editPayDetailButton = new JButton("修改支付明细");
        editPayDetailButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                int selectedRow = detail.getSelectedRow();
                if (selectedRow != -1) {
                    try {
                        showEditPayDetailDialog(selectedRow);
                    } catch (SQLException ex) {
                        throw new RuntimeException(ex);
                    }
                } else {
                    JOptionPane.showMessageDialog(null, "请选择要修改的支付明细");
                }
            }
        });

        JButton deletePayDetailButton = new JButton("删除支付明细");
        deletePayDetailButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                int selectedRow = detail.getSelectedRow();
                if (selectedRow != -1) {
                    int did = (int) model.getValueAt(selectedRow, 0); // 假设第一列是支付明细编号
                    PayDetailDao dao = new PayDetailDao();
                    dao.deletePayDetail(did);
                    model.removeRow(selectedRow);
                } else {
                    JOptionPane.showMessageDialog(null, "请选择要删除的支付明细");
                }
            }
        });

        JButton queryPayDetailButton = new JButton("查询支付明细");
        queryPayDetailButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                showQueryPayDetailDialog();
            }
        });

        JButton exportPayDetailButton = new JButton("导出支付明细数据");
        exportPayDetailButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                showExportPayDetailDialog();
            }
        });

        Jbutton.add(addPayDetailButton);
        Jbutton.add(editPayDetailButton);
        Jbutton.add(deletePayDetailButton);
        Jbutton.add(queryPayDetailButton);
        Jbutton.add(exportPayDetailButton);

        getContentPane().add(Jbutton, BorderLayout.SOUTH);
    }
}
